package first_practice;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author ZhiWen Ren
 * @version 1.0
 * @description: LeetCode-199-二叉树的右视图
 * @date 2025/4/14 10:25
 */
public class Solution199 {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        if (root == null)
            return ans;
        Queue<TreeNode> rightNodesQueue = new LinkedList<>();
        rightNodesQueue.offer(root);

        // 只需要对二叉树进行层序遍历，然后在ans中加入当前层的最后一个元素的val
        while (!rightNodesQueue.isEmpty()) {
            int size = rightNodesQueue.size();
            for (int i = 0; i < size; i++) {
                root = rightNodesQueue.poll();
                if (root.left != null)
                    rightNodesQueue.add(root.left);
                if (root.right != null)
                    rightNodesQueue.add(root.right);
                if (i == size - 1)
                    ans.add(root.val); // 只需要加入右视图的节点
            }
        }

        return ans;
    }
}
